
import java.awt.GridLayout;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


import messagepasser.DocInfo;
import messagepasser.Document;
import messagepasser.UserInfo;

public class Client_Servant extends UnicastRemoteObject implements Client {
	
	LoggedIn mainWindow;
	int userid;
		
	public Client_Servant(LoggedIn i, int userid) throws RemoteException {
		mainWindow = i;
		this.userid = userid;
	}

	@Override
	public void newDocument(int docid) throws RemoteException {
		System.out.println ("new user");
		Object[] OkCancel = { "Ok", "Cancel" };
		JLabel jl = new JLabel("Permissions Changed");
		JOptionPane.showOptionDialog(null, jl, "Permissions Changed", JOptionPane.DEFAULT_OPTION, JOptionPane.NO_OPTION, null, OkCancel, OkCancel[0]);
		
	}

	@Override
	public void newUserOnline(UserInfo u) throws RemoteException {
		
		boolean newRegUser = true; 
		
		for (UserInfo user : mainWindow.users) {
			if (user.getUserid() == u.getUserid()) {
				user.setIpaddr(u.getIpaddr());
				user.setOnlinestatus(u.isOnlinestatus());
				user.setPort(u.getPort());
				newRegUser = false;
				for (Document doc : mainWindow.userDocs) {
					doc.getMyPasser().updateUserInfo(u);
				}
				break;
			}
		}
		
		if (newRegUser) {
			mainWindow.users.add(u);
		}
		
		if (mainWindow.userNames.contains(u.getUsername()) == false) {
			mainWindow.userNames.add(u.getUsername());
		}
		mainWindow.getOnlineUsers().setListData(mainWindow.userNames);
		
	}	
	
	public void userOffline(int userId) throws RemoteException {
		System.out.println ("logout called");
		
		for (UserInfo user : mainWindow.users) {
			if (user.getUserid() == userId) {
				user.setIpaddr(null);
				user.setOnlinestatus(false);
				user.setPort(0);
				mainWindow.userNames.remove(user.getUsername());
				break;
			}
		}
		
		mainWindow.getOnlineUsers().setListData(mainWindow.userNames);
		
	}

	@Override
	public int getUserId() throws RemoteException {
		// TODO Auto-generated method stub
		return userid;
	}	
	
}
